﻿using Dyao.Book.Contract;
using Dyao.Book.Repository.Abstractions;
using Foundation.Core;

namespace Dyao.Book.Application
{
    public abstract class BaseBookChapterPlugins : ITransientDependency
    {
        protected readonly IBookCatalogueRepository _catalogueRepository;

        /// <summary>
        /// Key
        /// </summary>
        public abstract string SourceKey { get; set; }

        public BaseBookChapterPlugins(IBookCatalogueRepository catalogueRepository)
        {
            _catalogueRepository = catalogueRepository;
        }

        /// <summary>
        /// 是否还有需要匹配的章节
        /// </summary>
        /// <param name="bookId">书籍编号</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<bool> HasMatchChapterSourceAsync(string bookId, CancellationToken cancellationToken)
        {
            var chapters = await _catalogueRepository.GetNotMatchListByBookIdAsync(bookId, bc => new { bc.ID }, cancellationToken);
            return chapters.Any();
        }

        /// <summary>
        /// 获取书源
        /// </summary>
        /// <param name="args">章节插件参数</param>
        /// <returns></returns>
        public BookSourceDto GetBookSource(BookChapterPluginsArgs args)
        {
            var setting = GetSourceSetting(args);
            return args.BookSources.FirstOrDefault(b => b.SourceKey == setting.SourceKey);
        }

        /// <summary>
        /// 获取书源配置
        /// </summary>
        /// <param name="args">章节插件参数</param>
        /// <returns></returns>
        public BookSourceWarehouseDto GetSourceSetting(BookChapterPluginsArgs args)
        {
            var setting = args.SourceSettings.FirstOrDefault(s => s.SourceKey == SourceKey);
            return setting;
        }


        /// <summary>
        /// 爬取章节信息
        /// </summary>
        /// <param name="args">插件参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public abstract Task SpiderChapterAsync(BookChapterPluginsArgs args, CancellationToken cancellationToken);
    }
}
